<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="120px" class="advanced-search-form">
      <el-row :gutter="15">
        <!-- 第一行 -->
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="商户ID" prop="storeInfoId">
            <el-input
                v-model="queryParams.storeInfoId"
                placeholder="请输入关联商户ID"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="商品SKU ID" prop="skuId">
            <el-input
                v-model="queryParams.skuId"
                placeholder="请输入商品SKU ID"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="关联订单号" prop="orderNo">
            <el-input
                v-model="queryParams.orderNo"
                placeholder="请输入关联订单号"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="锁定数量" prop="lockQuantity">
            <el-input
                v-model="queryParams.lockQuantity"
                placeholder="请输入锁定数量"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第二行 -->
      <el-row :gutter="15">
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="锁定状态" prop="lockStatus">
            <el-select
                v-model="queryParams.lockStatus"
                placeholder="请选择锁定状态"
                clearable
                style="width: 100%; min-width: 200px"
            >
              <el-option
                  v-for="dict in stock_lock_record_lock_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="锁定时间" prop="lockTime">
            <el-date-picker
                clearable
                v-model="queryParams.lockTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择锁定时间"
                style="width: 100%"
            />
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="释放/出库时间" prop="unlockTime">
            <el-date-picker
                clearable
                v-model="queryParams.unlockTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择释放/出库时间"
                style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="逻辑删除标志" prop="delFlag">
            <el-select
                v-model="queryParams.delFlag"
                placeholder="请选择逻辑删除标志"
                clearable
                style="width: 100%; min-width: 200px"
            >
              <el-option
                  v-for="dict in del_flag"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 操作按钮 -->
      <el-row>
        <el-col :span="24" style="text-align: right; padding-right: 10px;">
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['core:StockLockRecord:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['core:StockLockRecord:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['core:StockLockRecord:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['core:StockLockRecord:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="StockLockRecordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="id" />
      <el-table-column label="商户" align="center">
        <template #default="scope">
          <span>{{ scope.row.storeInfoId }}-{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品SKU ID" align="center" prop="skuId" />
      <el-table-column label="关联订单号" align="center" prop="orderNo" />
      <el-table-column label="锁定数量" align="center" prop="lockQuantity" />
      <el-table-column label="锁定状态" align="center" prop="lockStatus">
        <template #default="scope">
          <dict-tag :options="stock_lock_record_lock_status" :value="scope.row.lockStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="逻辑删除标志" align="center" prop="delFlag">
        <template #default="scope">
          <el-tag
              :type="scope.row.delFlag === '0' ? 'success' : 'danger'"
              :effect="scope.row.delFlag === '0' ? 'light' : 'plain'"
          >
            <dict-tag :options="del_flag" :value="scope.row.delFlag"/>
          </el-tag>

        </template>
      </el-table-column>
      <!-- 表格中的时间列修改 -->
      <el-table-column label="锁定时间" align="center" prop="lockTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.lockTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="释放/出库时间" align="center" prop="unlockTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.unlockTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['core:StockLockRecord:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['core:StockLockRecord:remove']">删除</el-button>
          <el-button link type="success" icon="Refresh" @click="handleRecover(scope.row)" v-hasPermi="['core:StockLockRecord:edit']">
            误删恢复
          </el-button>
          <el-button link type="info" icon="View" @click="handleViewDetails(scope.row.orderNo)" v-hasPermi="['core:StockTransactionRecord:view']">
            查看详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改库存锁定记录对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="StockLockRecordRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商户" prop="storeInfoId">
          <el-select
              v-model="form.storeInfoId"
              placeholder="请选择商户"
              filterable
              clearable
              style="width: 100%"
          >
            <el-option
                v-for="store in storeOptions"
                :key="store.id"
                :label="`${store.id}-${store.name}`"
                :value="store.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品SKU ID" prop="skuId">
          <el-input v-model="form.skuId" placeholder="请输入商品SKU ID" />
        </el-form-item>
        <el-form-item label="关联订单号" prop="orderNo">
          <el-input v-model="form.orderNo" placeholder="请输入关联订单号" />
        </el-form-item>
        <el-form-item label="锁定数量" prop="lockQuantity">
          <el-input v-model="form.lockQuantity" placeholder="请输入锁定数量" />
        </el-form-item>
        <el-form-item label="锁定状态" prop="lockStatus">
          <el-select v-model="form.lockStatus" placeholder="请选择锁定状态">
            <el-option
              v-for="dict in stock_lock_record_lock_status"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 对话框中的时间选择器修改 -->
        <el-form-item label="锁定时间" prop="lockTime">
          <el-date-picker clearable
                          v-model="form.lockTime"
                          type="datetime"
                          value-format="YYYY-MM-DD HH:mm:ss"
                          placeholder="请选择锁定时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="释放/出库时间" prop="unlockTime">
          <el-date-picker clearable
                          v-model="form.unlockTime"
                          type="datetime"
                          value-format="YYYY-MM-DD HH:mm:ss"
                          placeholder="请选择释放/出库时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="逻辑删除标志" prop="delFlag">
          <el-select v-model="form.delFlag" placeholder="请选择逻辑删除标志">
            <el-option
              v-for="dict in del_flag"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 在template部分修改订单详情弹窗 -->
    <!-- 修改订单详情弹窗部分 -->
    <el-dialog
        title="订单详情"
        v-model="detailsDialogVisible"
        width="80%"
        append-to-body
        @close="closeDetailsDialog"
    >
      <!-- 上半部分：订单基本信息 -->
      <div class="order-info-section">
        <el-descriptions :column="2" border size="medium">
          <!--          <el-descriptions-item label="订单ID" label-class-name="bold-label">{{ shopOrderDetails.id || '-' }}</el-descriptions-item>-->
          <el-descriptions-item label="订单编号" label-class-name="bold-label">{{ shopOrderDetails.orderNo || '-' }}</el-descriptions-item>
          <el-descriptions-item label="订单状态" label-class-name="bold-label">
            <dict-tag
                v-if="shopOrderDetails.status"
                :options="order_status"
                :value="shopOrderDetails.status"
            />
          </el-descriptions-item>
          <el-descriptions-item label="交易时间" label-class-name="bold-label">{{ parseTime(shopOrderDetails.createTime) || '-' }}</el-descriptions-item>
          <el-descriptions-item label="商户名称" label-class-name="bold-label">{{ storeInfo?.name || '-' }}</el-descriptions-item>
          <el-descriptions-item label="联系人| 联系电话" label-class-name="bold-label">{{ storeInfo?.contactName || '-' }} {{ storeInfo?.contactPhone || '-' }}</el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 分割线 -->
      <el-divider></el-divider>

      <!-- 下半部分：商品明细 -->
      <div class="order-items-section">
        <h4>商品明细</h4>
        <!-- 修改商品明细表格，添加规格列 -->
        <el-table
            :data="orderItems"
            border
            style="width: 100%"
            size="small"
        >
          <el-table-column prop="id" label="ID" width="80" align="center" />
          <el-table-column prop="skuId" label="SKU ID" width="220" align="center" />
          <el-table-column prop="spuName" label="商品名称" width="220" align="center">
            <template #default="{row}">
              {{ row.spuName || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="spec" label="规格" width="300" align="center">
            <template #default="{row}">
              {{ row.spec || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量" width="120" align="right" />
          <el-table-column prop="price" label="单价(元)" width="150" align="right">
            <template #default="{row}">
              {{ row.price?.toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDetailsDialog">关闭</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="StockLockRecord">
import { listStockLockRecord, getStockLockRecord, delStockLockRecord, addStockLockRecord, updateStockLockRecord } from "@/api/core/StockLockRecord"
import { listShoporder, getShoporder } from "@/api/transaction/shoporder";
import {listStoreInfo , getStoreInfo} from "@/api/core/storeInfo.js";
import {getShoporderitem,listShoporderitem } from "@/api/transaction/shoporderitem.js";
import {listSku,getSku} from "@/api/transaction/sku.js";
import {listSpuVo,getSpu} from "@/api/transaction/spu.js"; // 导入 API 请求方法
const { proxy } = getCurrentInstance()
const { stock_lock_record_lock_status, del_flag } = proxy.useDict('stock_lock_record_lock_status', 'del_flag')

const StockLockRecordList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const shopOrderDetails = ref(null);
const detailsDialogVisible = ref(false);

// 添加商户信息响应式变量
const storeInfo = ref(null)
const orderItems = ref([]); // 存储订单商品列表

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    storeInfoId: null,
    skuId: null,
    orderNo: null,
    lockQuantity: null,
    lockStatus: null,
    lockTime: null,
    unlockTime: null,
    delFlag: 0,
  },
  rules: {
    storeInfoId: [
      { required: true, message: "关联商户信息表id不能为空", trigger: "blur" }
    ],
    skuId: [
      { required: true, message: "商品SKU ID不能为空", trigger: "blur" }
    ],
    orderNo: [
      { required: true, message: "关联订单号不能为空", trigger: "blur" }
    ],
    lockQuantity: [
      { required: true, message: "锁定数量不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)


// 在响应式变量部分添加
const storeOptions = ref([]); // 存储商户选项

// 在methods部分添加获取商户列表的方法
function getStoreOptions() {
  listStoreInfo({
    pageNum: 1,
    pageSize: 1000  // 设置足够大的pageSize获取所有商户
  }).then(response => {
    storeOptions.value = response.rows;
  });
}

// 在created/mounted生命周期中调用
onMounted(() => {
  getStoreOptions();
});

/** 查询库存锁定记录列表 */
function getList() {
  loading.value = true;
  listStockLockRecord(queryParams.value).then(response => {
    StockLockRecordList.value = response.rows;
    total.value = response.total;

    // 获取所有商户信息并关联到表格数据
    const storeIds = [...new Set(response.rows.map(item => item.storeInfoId))];
    if (storeIds.length > 0) {
      listStoreInfo({ ids: storeIds.join(',') }).then(storeResponse => {
        const storeMap = new Map();
        storeResponse.rows.forEach(store => {
          storeMap.set(store.id, store);
        });

        // 将商户名称合并到交易记录中
        StockLockRecordList.value = response.rows.map(record => {
          return {
            ...record,
            name: storeMap.get(record.storeInfoId)?.name || '未知商户'
          };
        });
      }).finally(() => {
        loading.value = false;
      });
    } else {
      loading.value = false;
    }
  }).catch(() => {
    loading.value = false;
  });
}


// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    storeInfoId: null,
    skuId: null,
    orderNo: null,
    lockQuantity: null,
    lockStatus: null,
    lockTime: null,
    unlockTime: null,
    delFlag: 0,
    createTime: null
  }
  proxy.resetForm("StockLockRecordRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加库存锁定记录"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getStockLockRecord(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改库存锁定记录"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["StockLockRecordRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateStockLockRecord(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addStockLockRecord(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 - 改为逻辑删除 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认将库存锁定记录编号为"' + _ids + '"的数据项设为删除状态？').then(function() {
    // 改为调用更新状态的API
    return updateStockLockRecord({ id: _ids, delFlag: '1' })
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("操作成功")
  }).catch(() => {})
}
/** 恢复按钮操作 */
function handleRecover(row) {
  const _id = row.id
  proxy.$modal.confirm('是否确认恢复库存锁定记录编号为"' + _id + '"的数据项？').then(function() {
    return updateStockLockRecord({ id: _id, delFlag: '0' })
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("恢复成功")
  }).catch(() => {})
}


/** 查看详情按钮操作 */
function handleViewDetails(orderNo) {
  if (!orderNo) {
    proxy.$modal.msgWarning("该记录没有关联的业务单号");
    return;
  }

  loading.value = true;
  shopOrderDetails.value = null;
  storeInfo.value = null;
  orderItems.value = [];

  listShoporder({ orderNo: orderNo })
      .then(response => {
        if (response.rows?.length > 0) {
          const shopOrderId = response.rows[0].id;
          return getShoporder(shopOrderId).then(orderResponse => {
            shopOrderDetails.value = orderResponse.data;
            if (orderResponse.data.storeId) {
              return getStoreInfo(orderResponse.data.storeId).then(storeResponse => {
                storeInfo.value = storeResponse.data;
                return shopOrderId;
              });
            }
            return shopOrderId;
          });
        } else {
          throw new Error("未找到对应的订单信息");
        }
      })
      .then(shopOrderId => {
        return listShoporderitem({ orderId: shopOrderId }).then(itemsResponse => {
          // 第一步：获取所有SKU的详细信息（包含spuId）
          const skuPromises = itemsResponse.rows.map(item => {
            return getSku(item.skuId).then(skuResponse => {
              return {
                ...item,
                spec: skuResponse.data.spec,
                spuId: skuResponse.data.spuId // 从SKU信息中获取spuId
              };
            });
          });

          return Promise.all(skuPromises);
        });
      })
      .then(itemsWithSku => {
        // 第二步：获取所有SPU的名称
        const spuPromises = itemsWithSku.map(item => {
          if (!item.spuId) {
            return Promise.resolve({
              ...item,
              spuName: '无SPU信息'
            });
          }
          return getSpu(item.spuId).then(spuResponse => {
            return {
              ...item,
              spuName: spuResponse.data.name || '未知商品'
            };
          }).catch(() => {
            return {
              ...item,
              spuName: '获取失败'
            };
          });
        });

        return Promise.all(spuPromises);
      })
      .then(itemsWithFullDetails => {
        orderItems.value = itemsWithFullDetails;
        detailsDialogVisible.value = true;
      })
      .catch(err => {
        proxy.$modal.msgError("获取详情失败: " + (err.message || err));
      })
      .finally(() => {
        loading.value = false;
      });
}

// 修改关闭弹窗方法，重置商户信息
function closeDetailsDialog() {
  detailsDialogVisible.value = false
  storeInfo.value = null
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('core/StockLockRecord/export', {
    ...queryParams.value
  }, `StockLockRecord_${new Date().getTime()}.xlsx`)
}

getList()
</script>
<style scoped>
.advanced-search-form {
  padding: 18px 10px 0 10px;
  background: #f8f8f8;
  border-radius: 4px;
  margin-bottom: 15px;
}
.advanced-search-form .el-form-item {
  margin-bottom: 15px;
}
.order-info-section {
  margin-bottom: 20px;
}

.order-items-section {
  margin-top: 20px;
}

.order-items-section h4 {
  margin-bottom: 15px;
  font-size: 16px;
  color: #333;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>